# -*- coding:utf8 -*-
#encoding = utf-8

from flask import Flask
from flask import Flask,request,g,render_template,redirect,url_for,abort,session
from flask import make_response,Response,send_from_directory
import redis
from redis import StrictRedis
from flask_session import Session
import sys,os
import json
import time
from datetime import datetime,timedelta
from io import StringIO, BytesIO

import api.open_redis as open_redis


import random

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS',silent=True)

app.config['SECRET_KEY']=os.urandom(24)   #设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
app.config['PERMANENT_SESSION_LIFETIME']=60*60*24 #session长期有效，则设定session生命周期，整数秒，默认大概不到3小时。

app.config['SESSION_TYPE'] = 'redis'  # session类型为redis
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前缀
app.config['SESSION_REDIS'] = StrictRedis(host='127.0.0.1', port='6379')#, password='')  # 用于连接redis的配置

#上传文件最大 2MB
app.config['MAX_CONTENT_LENGTH'] = 20*1024*1024



#声明 蓝图

#登陆模块
from api.login import login
app.register_blueprint(login)
import api.login as login_function


#查询模块
from api.query import query
app.register_blueprint(query)
import api.query as query_function


#收藏模块
from api.collect import collect
app.register_blueprint(collect)
import api.collect as collect_function


#用户模块
from api.user import user
app.register_blueprint(user)
import api.user as user_function



#PC端显示模块
from api.pc_home import pchome
app.register_blueprint(pchome)
import api.pc_home as pchome_function


#社区模块
from api.shequ import shequ
app.register_blueprint(shequ)
import api.shequ as shequ_function



#使用公用方法
import api.public as pub


Session(app)

def Response_headers(content):  
    resp = Response(content)  
    resp.headers['Access-Control-Allow-Origin'] = '*'  
    return resp  






#首页
@app.route('/', methods=['POST','GET'])
def index_pg():
    home_list = ["美妆","iphone","口红","香水","华为"]
    getkeys = random.sample(home_list, 1)[0]
    getdatas = query_function.home_query_1(getkeys)
    #print(getdatas)
    return_list = []
    for datasinfo in getdatas:
        
        return_list.append(query_function.format_codlist(datasinfo))
    #print(return_list)

    #推荐分类栏数据
    tjfl_info = user_function.get_tj_fenlei()

    #  总访问量 allcount
    count = pub.get_PV()
    return render_template('home_sp.html',
                            home=1,
                            datalist=return_list,
                            keys=getkeys,
                            tjfl = tjfl_info,
                            allcount = count)



#分类查询接口
@app.route('/flpg', methods=['POST','GET'])
def fenlei_pg():
    return render_template('fenlei.html')





#获取IP
def get_user_ip():
    print(request.remote_addr)
    return request.remote_addr


#用户身份识别
def userACC():
    userToken=request.cookies.get('user_token')
    print("[Get Cookies] = "+str(userToken))
    username=request.cookies.get('user_name')
    print("[Get username] = "+str(username))

    keys = session.get(userToken)
    print("[Get keys] = "+str(keys))
    if userToken != None and keys == username:
        return True
    else:
        return False




#注册
@app.route('/reg', methods=['POST','GET'])
def reg_pg():
    return render_template('reg.html',my=1)




#我的收藏
@app.route('/sc', methods=['POST','GET'])
def sc_pg():
    if userACC() == True:
        
        useruuid=request.cookies.get('user_uuid')
        print("userUUID = "+ str(useruuid))

        #print(collect_function.get_my_sc(hbsj_user_id))

        getdatas = collect_function.get_my_sc(useruuid)

        return_list = []
        for datasinfo in getdatas:
            
            return_list.append(collect_function.sc_codlist(datasinfo))

        print(return_list)

        if return_list == []:
            print("list is null")
            return_null = 1
            
        else:
            print("have datas")
            return_null = None
        
        return render_template('shouchang.html',sc=1,datalist=return_list,returnnull=return_null)
    else:
        
        return redirect('/loginpg')
    


#第三分链接跳转
@app.route('/goto', methods=['POST','GET'])
def goto_pg():
    if request.method == "GET":
        urls = request.args.get('urls')
        titles = request.args.get('names')
    print(urls)
    return render_template('goto_3fang.html',home=1,url=urls,title=titles)



@app.route('/downloadpg',methods=['POST','GET'])
def download_pg():
    return render_template('downapp.html',home=1)



@app.route('/downloadapp',methods=['POST','GET'])
def download_app():

    Man_API_Path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    print(Man_API_Path)
    filepath = Man_API_Path+"/hbsj_v0.21/"
    filename = "hbsjAPP-v0.1.8.apk"
    #普通下载
    response = make_response(send_from_directory(filepath, filename, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
    return send_from_directory(filepath, filename, as_attachment=True)
    #return "0"
    '''
    #流式读取
    def send_file():
        store_path = fullfilename
        with open(store_path, 'rb') as targetfile:
            while 1:
                data = targetfile.read(20 * 1024 * 1024)   # 每次读取20M
                if not data:
                    break
                yield data
    
    response = Response(send_file(), content_type='application/octet-stream')
    response.headers["Content-disposition"] = 'attachment; filename=%s' % filename   # 如果不加上这行代码，导致下图的问题
    return response
    '''


#问卷调查
@app.route('/wenjuan',methods=['POST','GET'])
def wen_juan():
    return render_template('wenjuan.html',home=1)


#问卷调查
@app.route('/wenjuan_post',methods=['POST','GET'])
def wen_juan_opst():
    return render_template('wenjuan.html',home=1)




@app.errorhandler(403)
def page_not_found(error):
    content = json.dumps({"error_code": "403"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(404)
def page_not_found(error):
    content = json.dumps({"error_code": "404"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(400)
def page_not_found(error):
    content = json.dumps({"error_code": "400"})
    # resp = Response(content)
    # resp.headers['Access-Control-Allow-Origin'] = '*'
    resp = Response_headers(content)
    return resp
    # return "error_code:400"

@app.errorhandler(410)
def page_not_found(error):
    content = json.dumps({"error_code": "410"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(500)
def page_not_found(error):
    content = json.dumps({"error_code": "500"})
    resp = Response_headers(content)
    return resp

    



if __name__ == '__main__':
    #启动redis
    open_redis.start_redis()
    app.run(host="0.0.0.0",port=9080,debug=True,threaded=True)